/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dialogs.usuario;

import dao.DaoUsuario;
import dialogs.emprestimos.JDialogEmprestimos;
import dialogs.emprestimos.JDialogRegistrarPagamento;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import libcontrol.model.Usuario;

/**
 *
 * @author filipe
 */
public class JDialogListarUsuario extends javax.swing.JDialog {

    private JDialog jDialog;

    /**
     * Creates new form JFrameListarUsuario
     */
    public JDialogListarUsuario(JFrame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        buttonGroupTipoPesquisa.add(jRadioButtonNome);
        buttonGroupTipoPesquisa.add(jRadioButtonCpf);
        atualizarTabela(new DaoUsuario().list());        
    }

    public JDialogListarUsuario(JFrame parent, boolean modal, JDialog jDialog) {
        super(parent, modal);
        initComponents();
        buttonGroupTipoPesquisa.add(jRadioButtonNome);
        buttonGroupTipoPesquisa.add(jRadioButtonCpf);
        atualizarTabela(new DaoUsuario().list());        
        this.jDialog = jDialog;
        jButtonVerUsuario.setText("Selecionar");
        jButtonVerUsuario.setIcon(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroupTipoPesquisa = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jTextFieldBuscar = new javax.swing.JTextField();
        jPanelTipoPesquisa = new javax.swing.JPanel();
        jRadioButtonNome = new javax.swing.JRadioButton();
        jRadioButtonCpf = new javax.swing.JRadioButton();
        jButtonBuscar = new javax.swing.JButton();
        jButtonFechar = new javax.swing.JButton();
        jButtonVerUsuario = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableListarUsuario = new javax.swing.JTable();

        setPreferredSize(new java.awt.Dimension(700, 600));

        jPanelTipoPesquisa.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder("Tipo de Pesquisa")));
        jPanelTipoPesquisa.setToolTipText("");
        jPanelTipoPesquisa.setFont(new java.awt.Font("Arial Black", 0, 12)); // NOI18N

        jRadioButtonNome.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
        jRadioButtonNome.setSelected(true);
        jRadioButtonNome.setText("Nome");

        jRadioButtonCpf.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
        jRadioButtonCpf.setText("CPF");

        javax.swing.GroupLayout jPanelTipoPesquisaLayout = new javax.swing.GroupLayout(jPanelTipoPesquisa);
        jPanelTipoPesquisa.setLayout(jPanelTipoPesquisaLayout);
        jPanelTipoPesquisaLayout.setHorizontalGroup(
            jPanelTipoPesquisaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelTipoPesquisaLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jRadioButtonNome)
                .addGap(41, 41, 41)
                .addComponent(jRadioButtonCpf)
                .addGap(0, 33, Short.MAX_VALUE))
        );
        jPanelTipoPesquisaLayout.setVerticalGroup(
            jPanelTipoPesquisaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelTipoPesquisaLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelTipoPesquisaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jRadioButtonNome)
                    .addComponent(jRadioButtonCpf))
                .addContainerGap(18, Short.MAX_VALUE))
        );

        jButtonBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/pesquisar.png"))); // NOI18N
        jButtonBuscar.setText("Buscar");
        jButtonBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBuscarActionPerformed(evt);
            }
        });

        jButtonFechar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/cancelar.png"))); // NOI18N
        jButtonFechar.setText("Fechar");
        jButtonFechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonFecharActionPerformed(evt);
            }
        });

        jButtonVerUsuario.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/ver.png"))); // NOI18N
        jButtonVerUsuario.setText("Ver Usuário");
        jButtonVerUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonVerUsuarioActionPerformed(evt);
            }
        });

        jTableListarUsuario.setFont(new java.awt.Font("Arial Black", 0, 12)); // NOI18N
        jTableListarUsuario.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nome", "CPF"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableListarUsuario.setColumnSelectionAllowed(true);
        jTableListarUsuario.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTableListarUsuario);
        jTableListarUsuario.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTableListarUsuario.getColumnModel().getColumn(1).setPreferredWidth(100);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanelTipoPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jTextFieldBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 333, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 189, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jButtonFechar, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButtonVerUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(25, 25, 25))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(61, 61, 61)
                .addComponent(jPanelTipoPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButtonBuscar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jTextFieldBuscar))
                .addGap(22, 22, 22)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonVerUsuario)
                    .addComponent(jButtonFechar))
                .addGap(35, 35, 35))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuscarActionPerformed
        List<Usuario> listUsuarios;
        if (jRadioButtonNome.isSelected()) {
            listUsuarios = new DaoUsuario().listByNome(jTextFieldBuscar.getText());
        } else {
            Usuario usuario = new DaoUsuario().findByCpf(jTextFieldBuscar.getText());
            listUsuarios = new ArrayList<>();
            if (usuario != null) {
                listUsuarios.add(usuario);
            }
        }
        if (listUsuarios.isEmpty()) {
            JOptionPane.showMessageDialog(this, "A busca não retornou resultados.", "Busca", JOptionPane.INFORMATION_MESSAGE);
        } else {
            atualizarTabela(listUsuarios);            
        }
    }//GEN-LAST:event_jButtonBuscarActionPerformed

    private void jButtonVerUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonVerUsuarioActionPerformed
        int selectedRow = jTableListarUsuario.getSelectedRow();
        if (selectedRow != -1) {
            String cpf = (String) jTableListarUsuario.getModel().getValueAt(selectedRow, 1);
            Usuario usuario = new DaoUsuario().findByCpf(cpf);
            if (usuario != null) {
                if (jButtonVerUsuario.getText().equals("Selecionar")) {
                    if (jDialog instanceof JDialogEmprestimos) {
                        ((JDialogEmprestimos) jDialog).setUsuario(usuario);
                    } else {
                        ((JDialogRegistrarPagamento) jDialog).setUsuario(usuario);
                    }
                    dispose();
                } else {                    
                    new JDialogVerUsuario((JFrame) getParent(), true, usuario).setVisible(true);
                    atualizarTabela(new DaoUsuario().list());
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "Nenhum usuário selecionado na tabela!", "Erro", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButtonVerUsuarioActionPerformed

    private void jButtonFecharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFecharActionPerformed
        dispose();
    }//GEN-LAST:event_jButtonFecharActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroupTipoPesquisa;
    private javax.swing.JButton jButtonBuscar;
    private javax.swing.JButton jButtonFechar;
    private javax.swing.JButton jButtonVerUsuario;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanelTipoPesquisa;
    private javax.swing.JRadioButton jRadioButtonCpf;
    private javax.swing.JRadioButton jRadioButtonNome;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableListarUsuario;
    private javax.swing.JTextField jTextFieldBuscar;
    // End of variables declaration//GEN-END:variables

    private void atualizarTabela(List<Usuario> list) {
        DefaultTableModel model = (DefaultTableModel) jTableListarUsuario.getModel();
        model.setNumRows(0);
        Object[] rowData = new Object[2];
        for (Usuario usuario : list) {
            rowData[0] = usuario.getNome();
            rowData[1] = usuario.getCpf();
            model.addRow(rowData);
        }
        jTableListarUsuario.setModel(model);
    }
}
